import React, { useState } from "react";
// 这种写法会在 webpack打包的时候打包进项目里面，尽量少用
import logo from "@/assets/images/logo.png";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
import "./index.less";
import { LoginApi } from "@/api";
import useToast from "@/hooks/useToast";
import { useNavigate } from "react-router-dom";

export default function Login() {
  // 用来表示当前是否是登录页面
  const [isLoginPage, setIsLoginPage] = useState(true);
  const [username, setUserName] = useState("12345678901");
  const [password, setUpassword] = useState("wolfcode123");
  const toast = useToast();
  const nav = useNavigate();
  const login = () => {
    LoginApi({ username, password })
      .then((res) => {
        if (res.errCode === 0) {
          toast("登录成功");
          // 登录成功后
          // 保存token
          localStorage.setItem("token", res.data);
          // 跳转到home
          nav("/home");
        }
      })
      .catch((err) => {
        toast(err.response.data.message, "error");
      });
  };
  const register = () => {};

  // 调用api函数，向服务器发请求
  const btnClick = () => {
    // 发请求前一定要进行表单验证 - 公用的
    // 手机号

    // 密码不能空

    // 判断当前是登录还是注册
    isLoginPage ? login() : register();
  };
  return (
    <div className="login">
      <section className="logo">
        <img src={logo} alt="" />
      </section>
      <section className="form">
        <div className="item">
          <TextField
            value={username}
            onChange={(e) => setUserName(e.target.value)}
            fullWidth
            variant="outlined"
            placeholder="请输入手机号"
          />
        </div>
        <div className="item">
          <TextField
            value={password}
            onChange={(e) => setUpassword(e.target.value)}
            fullWidth
            type="password"
            variant="outlined"
            placeholder="请输入密码"
          />
        </div>
        <div className="item">
          <Button fullWidth variant="contained" onClick={btnClick}>
            {isLoginPage ? "登录" : "注册"}
          </Button>
        </div>
      </section>
      <section className="to">
        <Button variant="text" onClick={() => setIsLoginPage(!isLoginPage)}>
          {isLoginPage ? "去注册" : "返回登录"}
        </Button>
      </section>
    </div>
  );
}
